import {BrowserWindow, ipcMain} from "electron";

const {autoUpdater} = require("electron-updater");
import {GiteeProvider} from './GiteeProvider'
import {EventEmitter} from "node:events";

const ev = new EventEmitter()

autoUpdater.disableDifferentialDownload = true
autoUpdater.disableWebInstaller = true
autoUpdater.forceDevUpdateConfig = true
autoUpdater.autoDownload = false
autoUpdater.setFeedURL({
  provider: "custom",
  // host: "gitcode.com",
  owner: 'jiang516',
  repo: 'gagamengprinter',
  token: '36a3a5f3b2235e9cc96bfcc59be22475',
  updateProvider: GiteeProvider
})

ipcMain.on("downloadUpdate", e => {
  // 开始下载设置为不可关闭
  const win = BrowserWindow.fromWebContents(e.sender)
  win?.setClosable(false)
  autoUpdater.downloadUpdate()
})
ipcMain.on("quitAndInstall", e => {
  autoUpdater.quitAndInstall(false, true)
})
let homeId
ipcMain.on("homeCheckUpdate", (e, {id}) => {
  homeId = id
  ev.once("result" + id, res => {
    homeId = null
    e.sender.send("result" + id, {res})
  })
  autoUpdater.checkForUpdates()
})
let updateWin: BrowserWindow

export async function checkForUpdates(win: BrowserWindow) {
  // autoUpdater.checkForUpdatesAndNotify({
  //   title: "新的更新已准备好安装",
  //   body: `嘎嘎猛打印版本{version}已下载，将在退出时自动安装`,
  // });
  updateWin = win
  autoUpdater.checkForUpdates()
}

autoUpdater.on('checking-for-update', () => {
  // console.log("正在检查更新")
  if (updateWin) {
    updateWin.webContents.send("checking-for-update")
  }
})

autoUpdater.on('update-available', (info) => {
  // console.log("info", info)
  // console.log("有更新需要进行更新")
  if (updateWin) {
    updateWin.webContents.send("update-available", info)
  }
  if (homeId) {
    ev.emit("result" + homeId, true)
  }
})

autoUpdater.on('update-not-available', (info) => {
  // console.log("已经是最新版本了，无需更新")
  if (updateWin) {
    updateWin.webContents.send("update-not-available", info)
  }
  if (homeId) {
    ev.emit("result" + homeId, false)
  }
})

autoUpdater.on('error', (err) => {
  // console.log("更新失败了")
  if (updateWin) {
    updateWin.webContents.send("error", err)
  }
})

autoUpdater.on('download-progress', (progressObj) => {
  // let log_message = "Download speed: " + progressObj.bytesPerSecond;
  // log_message = log_message + ' - Downloaded ' + progressObj.percent + '%';
  // log_message = log_message + ' (' + progressObj.transferred + "/" + progressObj.total + ')';
  // console.log("下载进度：", log_message);
  if (updateWin) {
    updateWin.webContents.send("download-progress", progressObj)
  }
})

autoUpdater.on('update-downloaded', (info) => {
  // console.log("下载完成")
  if (updateWin) {
    updateWin.webContents.send("update-downloaded", info)
  }
});